import {
  getQueryParam,
  IEnvironment,
  IStreamlineData,
  QueryParamKeys
} from '@amcax/base'
import {
  ctx2,
  dataManager,
  userEvents
} from '@app-cad/module';
import { CadEnvironments } from '@app-cad-env/index';
import { LeftPanel } from './widgets/LeftPanel';
import { setTreeData } from './widgets/LeftPanel/treeData';
import { Renderer3D, RendererMgr } from '@amcax/renderer';
import { createModelInfo, renderStreamlines } from './utils/renderModel';
import { fetchCamData } from './utils/ConcurrentRequest';
import { CAM_EVENT } from '@app-cad/common/Constants';

export const nextCamEnvironment: IEnvironment = {
  id: CadEnvironments.NextCam,
  label: 'cam',
  index: 0,
  showViewCube: true,
  init: () => {},
  load: async () => {
    const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
    const documentVersion = getQueryParam<string>(QueryParamKeys.VERSION);
    const paramsArr = ['model', 'trace'];

    // 并发请求速度会快
    const camDataArray = await fetchCamData(
      documentId,
      documentVersion,
      paramsArr,
    );
    // 三角化数据
    const triangleArray = camDataArray[0];
    const modelIds = triangleArray.map((item) => {
      return item.id;
    });

    //流线渲染数据
    const streamLineData: IStreamlineData[] = [];
    // 刀轨edge数据，方便取id 当作tree 的label
    const camData = [];
    // 刀轨数据
    const knifeData = camDataArray[1];
    // 获取所有刀轨数据colormap
    const colorMap: number[][][] = [];
    const scaler: number[][] = [];
    knifeData.forEach((item) => {
      camData.push(item.edge);
      const polylines = [item.edge.points.map((_item, index) => index)];
      // 将 '0.000':[] 转成[]
      colorMap.push(Object.values(item.color_map));
      streamLineData.push({
        id: item.edge.id,
        category: item.edge.category,
        arrows: [],
        points: item.edge.points,
        colors: [],
        polylines,
      });
      scaler.push(item.scaler);
    });
    const treceIds = camData.map((item) => {
      return item.id;
    });
    triangleArray.forEach((object) => {
      dataManager.addObjectsInfo(createModelInfo(object.id, true));
      if (object.faces && object.faces.length > 0) {
        object.faces.forEach((item) => {
          // 这里如果uvs length 为0 会报错
          if (item.uvs.length === 0) {
            delete item.uvs;
          }
        });
      }
    });
    setTreeData(modelIds, treceIds);
    const renderer = RendererMgr.getRender<Renderer3D>('3d');
    renderer.saveShapeDatas(triangleArray);
    await renderer.drawNewModels(modelIds);
    renderStreamlines(streamLineData, scaler, colorMap);
    userEvents.emit(CAM_EVENT.MODEL_LOADED);
    ctx2.viewer.sceneSetup.setToHomeView(400);
  },
  unload: async () => {},
  contextMenus: () => [],
  toolBar: () => <></>,
  leftPanel: () => <LeftPanel />,
  actionBar: () => <></>,
  assistLayer: () => <></>,
};
